package com.nitty.cash.loop.ui.activity

import android.graphics.Color
import android.os.Handler
import android.os.Looper
import android.view.View
import com.nitty.cash.loop.R
import com.nitty.cash.loop.common.CommonActivity
import com.nitty.cash.loop.configs.NittyApiPath
import com.nitty.cash.loop.configs.NittyApiUrl
import com.nitty.cash.loop.configs.NittyApiUrl.addCommonParams
import com.nitty.cash.loop.databinding.UiSettingBinding
import com.nitty.cash.loop.event.NittyEventPointType
import com.nitty.cash.loop.request.IHttpCallback
import com.nitty.cash.loop.ui.dialog.NittyClearDataDialog
import com.nitty.cash.loop.utils.helper.NittyOrderHelper
import com.nitty.cash.loop.utils.shared.NittySharedHelper
import org.json.JSONObject

/**
 * NittyCash
 * @Author wwdeng
 * @CreateTime: 2024/11/27 16:16
 * @Annotation：设置
 */
class SettingAct: CommonActivity() {
    lateinit var binding: UiSettingBinding
    override fun getNittyRootView(): View {
        binding = UiSettingBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initNittyView() {
        rootViewBinding.rootLayout.setBackgroundColor(Color.parseColor("#FFF8F8F8"))
        setNittyTitleBarVisibility(View.VISIBLE)
        setNittyBackBtnVisibility(View.VISIBLE)
        setNittyRightBtnRes(R.mipmap.img_customer_black)
        setNittyTextTitle(getString(R.string.menu_setting))
    }

    override fun initNittyListener() {
        //客服
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog("Setting Page")
            addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_CUSTOMER,"Setting Page")
        }

        //清空用户数据
        binding.btnClearData.setOnClickListener {
            addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_USER_DATA_CLEAR)
            //存在未结清的账单
            if (isUserSettingCheckUncleared()){
                showErrorTipsDialog(getString(R.string.user_data_clear_error),"Setting Page")
                return@setOnClickListener
            }
            showUserClearDataDialog()
        }

        //退出登录
        binding.btnLoginOut.setOnClickListener {
            addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_USER_LOGINOUT,"")
            //退出登录，需要移除用户保存的信息
            NittySharedHelper.onNittyUserLoginOut()
            Handler(Looper.getMainLooper()).postDelayed({
                onIntent(LoginAct::class.java)
            },300)
        }
    }

    override fun loadNittyData() {
        //获取版本名称
        val packageInfo = packageManager.getPackageInfo(this.packageName, 0)
        val versionCode = packageInfo.versionCode // 版本号（整数）
        binding.textVersion.text = String.format(getString(R.string.setting_version_name),packageInfo.versionName)
    }

    /**
     * 是否存在未结清的账单
     */
    private fun isUserSettingCheckUncleared(): Boolean{
        val orderList = NittyOrderHelper.getNittyOrderList()
        if (orderList.size == 0){
            return false
        }
        orderList.forEach {
            val orderStatus = it.optString("orderStatus")
            return when(orderStatus){
                "IN_REVIEW","LENDING","WAIT_REPAY" -> {
                    true
                }
                else -> {
                    false
                }
            }
        }
        return false
    }

    /**
     * 清空用户数据dialog
     */
    private fun showUserClearDataDialog(){
        val clearDialog = NittyClearDataDialog(this,object : NittyClearDataDialog.IDialogCallback{
            override fun onUserDataClearConfirmClick() {
                submitUserClearDataAction()
            }
        })
        clearDialog.setCancelable(true)
        clearDialog.setCanceledOnTouchOutside(true)
        clearDialog.show()
    }

    /**
     * 清除用户数据
     */
    private fun submitUserClearDataAction(){
        showNittyLoading()
        val httpUrl = NittyApiUrl.getHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("xd304965bcd9478080",NittyApiPath.NITTY_PATH.NITTY_API_USER_DATA_CLEAR_PATH)
        }
        doPostAction(httpUrl, params, object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                hiddenNittyLoading()
                //退出登录，需要移除用户保存的信息
                NittySharedHelper.onNittyUserLoginOut()
                onIntent(LoginAct::class.java)
            }
            override fun onRequestError(error: JSONObject) {
                showNittyToast(error.optString("errorMsg"))
            }
            override fun onRequestFinish() {
                hiddenNittyLoading()
            }
        })
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(NittyEventPointType.PAGE.NITTY_PAGE_USER_SETTING_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(NittyEventPointType.PAGE.NITTY_PAGE_USER_SETTING_END)
    }
}